<?php
/*
 * 盘点库存（新）
 * @author chamlinsun@qq.com
 */
class  Controller_Checkstore extends Controller_Admin {
    public function before(){
        try {
            ACL::Required('checkstore');
        } catch ( HTTP_Exception_403 $e ) {
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect ( URL::base (true) );
        }
        parent::before();
    }
    /*
     * 盘点库存重构首页
     */
    public function action_index() {
        $this->title = '盘点库存(新)';
        $view = View::factory('checkstore/index');
        
        $stor = new Checkstore();
        //$stor::hzDeliveryorders();
        //$stor::$lists = array();
        if(empty($_GET['warehouseid'])){
            $_GET['warehouseid'] = 5;
        }
        $page = $this->page($stor->doCondition());
        $stor->page = $page;
        $stor->getLimitLists();
        empty($_GET['download']) || $stor->download = 1;
        empty($_GET['download']) || $this->download($stor::$lists);
        //var_dump($stor::$lists);exit;
        $view->set('page',$page);
        $view->set('lists', $stor::$lists)
            ->set('get', $_GET)
            ->set('num', $stor::$num);

        $this->response->body($view); 
    }

    /*
     * 分页模块
     */
    public function page($count = NULL){
        return Pagination::factory(array(
            'total_items' => empty($count)?0:$count,
            'items_per_page' => 10,
            'uri' => $this->request->uri()
        ));
    }

    /*
     * 盘点库存数据下载
     */
    public function download($lists) {
        set_time_limit(0);
        ini_set('memory_limit','2048M');
        $downTime = date("Y-m-d H:i:s");
        $downDate = date("Y-m-d");

        require_once(Kohana::find_file('vendor','PHPExcel/PHPExcel/IOFactory'));
        $this->objReader = PHPExcel_IOFactory::createReader('Excel5');
        $objPHPExcel = new PHPExcel();
        $objPHPExcel->getProperties()
            ->setCreator("YKS")
            ->setLastModifiedBy("YKS")
            ->setTitle("Office 2003 XLSX Test Document")
            ->setSubject("Office 2003 XLSX Test Document")
            ->setDescription("Test document for Office 2003 XLSX, generated using PHP classes.")
            ->setKeywords("office 2003 openxml php")
            ->setCategory("Test result file");
        $objActSheet = $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet->setCellValue('A1','SKU');
        $objActSheet->setCellValue('B1','单据下载时间');
        $objActSheet->setCellValue('C1','品名');
        $objActSheet->setCellValue('D1','仓库');
        $objActSheet->setCellValue('E1','储位');
        $objActSheet->setCellValue('F1','盘点日期（xxxx-xx-xx）');
        $objActSheet->setCellValue('G1','库存量');
        $objActSheet->setCellValue('H1','实际盘点量');
        $objActSheet->setCellValue('I1','借料备注量');
        $objActSheet->setCellValue('J1','销售状态');

        $i        = 0;
        foreach($lists as $list){
            $key = $i+2;
            $objActSheet->setCellValue('A'.$key, $list['sku']);
            $objActSheet->setCellValue('B'.$key, $downTime);
            $objActSheet->setCellValue('C'.$key, $list['name']);
            $objActSheet->setCellValue('D'.$key, $list['warehouseid']);
            $objActSheet->setCellValue('E'.$key, $list['storage']);
            $objActSheet->setCellValue('F'.$key, $downDate);
            $objActSheet->setCellValue('G'.$key, $list['stock']);
            $objActSheet->setCellValue('H'.$key, $list['lend']);
            $objActSheet->setCellValue('I'.$key, '');
            $objActSheet->setCellValue('J'.$key, $list['status']);
            $i++;
        }

        $objPHPExcel->getActiveSheet()
            ->setTitle('新盘点库存');
        $objPHPExcel->setActiveSheetIndex(0);
        $day = date("m-d");
        $filename = $day."新盘点库存.xls";
        ob_end_clean();
        header("Content-Type: application/vnd.ms-excel; charset=utf-8");
        header('Content-Disposition: attachment;filename='.$filename);
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    //库存盘点上传重构
    public function action_upload(){
        set_time_limit(0);
        ini_set('memory_limit','2048M');
        require_once(Kohana::find_file('vendor','PHPExcel/PHPExcel/IOFactory'));

        $this->title = '盘点单';
        $time = date('Y-m-d H:i:s');
        if(isset($_GET['page'])&&$_GET['page']>1){
            $sql = "select op_time from pandians order by op_time desc limit 1";
            $date = DB::query(Database::SELECT,$sql)
                ->execute('newerp')
                ->current();
            if(isset($date['op_time'])){
                $time = $date['op_time'];
            }
        }

        $xls = (isset($_FILES['xls'])&&isset($_FILES['xls']['tmp_name']))?$_FILES['xls']['tmp_name']:'';
        if($xls){
            $objPHPExcel = PHPExcel_IOFactory::load($xls);
            $data = $objPHPExcel->getActiveSheet()->toArray(NULL,TRUE,TRUE,TRUE);
            $data = checkstore::checkxls($data);
            if($data['error'] != ''){
                $str = $data['error'];
            }
            unset($data['error']);
            if(count($data) == 1){
                $str = str_replace("<br/>",'',$str);
                if(empty($str)){
                    $str = "数据格式错误或数据为空导入失败";
                }
                header("Content-type: text/html; charset=utf-8");
                $alert_msg = "alert('{$str}');";
                $gourl = 'history.go(-1);';
                echo "<script>{$alert_msg}{$gourl}</script>";
                exit;
                $this->request->redirect("checksore/index");
            }
            $stor = new Checkstore();
            $i=0;
            foreach ($data as $key => $value) {
                $i++;
                if($i==1 || empty($value['A'])) continue;
                $res[] = array(
                    'sku'=> $value['A'],
                    'download_time'=>$value['B'],
                    'sku_name'=>$value['C'],
                    'warehouseid'=>$value['D'],
                    'storage_position'=>$value['E'],
                    'pd_time'=>$value['F'],
                    'quantity'=>$value['H'],//盘点数量
                    'quantity2'=>$value['G'],//实时库存量
                );
            }
            $lines = $stor->upload($res, $time);
        }
        $tablename = 'pandians';
        $result = $this->fenye2($tablename,$condition = array(
            'time' => $time,
            'items_per_page' => 10
        ));
        $view = View::factory('checkstore/upshow')
            ->set('datas',$result['datas'])
            ->set('pager_links',$result['pager_links'])
            ->set('lines',isset($lines['num'])?$lines['num']:array())
            ->set('final',isset($lines['error'])?$lines['error']:'')
            ->set('error',isset($str)?$str:'');
        $this->response->body($view);
    }

    private function fenye2($tablename,$condition){
        $items_per_page = $condition['items_per_page'];
        $pre = Pandianinout::getListInfoCondition(Pandianinout::getTotlePre($tablename),$condition,FALSE,$tablename);
        $pagination = Pagination::factory(array(
            'total_items' => Pandian::getTotle($pre),
            'view' => 'pagination/ajax_basic',
            'items_per_page' => $items_per_page,
            'uri' => $this->request->uri(),
        ));
        if(isset($_GET['page'])&&!empty($_GET['page'])){
            $offset = ($_GET['page']-1)*$items_per_page;
        }else{
            $offset = 0;
        }
        $pre = Pandianinout::getListInfoCondition(Pandianinout::getListPre($tablename),$condition,TRUE,$tablename);
        $datas = Pandianinout::getList($items_per_page,$offset,$pre);
        $pager_links = $pagination->render();
        $result = array(
            'datas' => $datas,
            'pager_links' => $pager_links
        );
        return $result;
    }
}